package by.parfen.game.service.coder.impl;

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;

import by.parfen.game.datamodel.GameSession;
import by.parfen.game.service.coder.GameSessionCoder;
import by.parfen.game.service.coder.JsonDateConverter;

public class GameSessionCoderImpl implements GameSessionCoder {

	@Override
	public JsonObject encode(GameSession gameSession) {
		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
		jsonBuilder.add("name", gameSession.getGameName());
		jsonBuilder.add("creationDate", new JsonDateConverter().date2string(gameSession.getCreationDate()));

		// JsonArray jsonArray = new JsonArray();
		// GameSessionService gameSessionService = new GameSessionServiceImpl();
		// List<GamePlayer> players =
		// gameSessionService.getGamePlayers(gameSession);
		// List<JsonObject> jsonPlayerList = new ArrayList<JsonObject>();
		// if (players != null) {
		// GamePlayerCoderImpl gamePlayerCoder = new GamePlayerCoderImpl();
		// for (GamePlayer player : players) {
		// jsonPlayerList.add(gamePlayerCoder.encode(player));
		// }
		// jsonBuilder.add("players", jsonPlayerList);
		// }

		JsonObject json = jsonBuilder.build();

		return json;
	}

	@Override
	public GameSession decode(JsonObject jsonGameSession) {
		GameSession gameSession = new GameSession();
		JsonObject json = Json.createReader(new StringReader(jsonGameSession.toString())).readObject();
		gameSession.setGameName(json.getString("name"));
		return gameSession;
	}

}
